package com.base.system.service.impl;

import com.base.system.bean.LoginForm;
import com.base.system.config.RandomValidateCode;
import com.base.system.config.jwt.JwtTokenProvider;
import com.base.system.service.EntranceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class EntranceServiceImpl implements EntranceService {
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public String login(LoginForm form, HttpSession session) {
        if(form.getCaptcha()!=null){
            //执行验证码操作
            RandomValidateCode code = new RandomValidateCode();
            code.checkRandCode(session,form.getCaptcha());
        }
        Authentication authentication = new UsernamePasswordAuthenticationToken(form.getUsername(), form.getPassword());
        //认证
        Authentication authenticate = authenticationManager.authenticate(authentication);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        //获取token
        String jwtToken = jwtTokenProvider.createJwtToken(authenticate);
        log.info("登录成功，取得token=>{}",jwtToken);
        return jwtToken;
    }
}
